<template>
  <div class="confirm">
    <div class="header">
      <div class="left">
        {{ typeName }}识别
        <img :src="typeImg" class="type-img" />
      </div>
      <img src="@/assets/img/fork.svg" class="right" @click="faceCancel" />
    </div>
    <div class="body">
      <div class="cus-msg">
        <div class="divide">
          <div class="border border-left"></div>
          <div class="txt">过磅人</div>
          <div class="border border-right"></div>
        </div>
        <div class="capture" v-if="type !== '4'">
          <img
            :src="capture"
            class="capture-img"
            :style="{
              borderColor:
                type === '2' ? (isRecognitionSuccessful ? '#7ED321' : '#FFDF25') : 'transparent'
            }"
          />
          <img
            :src="isRecognitionSuccessful ? successIcon : warnIcon"
            class="is-success"
            v-if="type === '2'"
          />
        </div>

        <div class="capture-retail" v-else>
          <img :src="file1" class="capture-img" />
          <img :src="file2" class="capture-img" />
        </div>
        <div class="cus-name">{{ cusName }}</div>
      </div>
      <div class="split"></div>
      <div class="other">
        <div class="divide">
          <div class="border border-left"></div>
          <div class="txt">过磅信息</div>
          <div class="border border-right"></div>
        </div>

        <div class="tips" v-if="type !== '4'">
          {{
            isRecognitionSuccessful
              ? `${typeName}识别成功 请确认信息！`
              : '您是首次操作请确认后跳转下页完成信息录入！'
          }}
        </div>
        <div class="msg" v-show="isRecognitionSuccessful && type !== '4'">
          今日已入场{{ carNum }}车，当前第{{ nextCarNum }}车待{{
            numberToChinese(weightTime + 1)
          }}磅称重
        </div>
        <div class="baseorders" v-if="type === '4'">
          <div
            class="base-order"
            :class="{ selected: item.selected }"
            v-for="item in retailBaseOrders"
            :key="item.id"
            @click="retailSelected(item)"
          >
            <div class="row">
              <div class="no">{{ item.baseOrderNo }}</div>
              <div class="cus-name">{{ item.supplierName }}</div>
              <div class="status" :style="{ color: item.statusColor }">{{ item.statusName }}</div>
            </div>
            <div class="row">
              <div class="weight">
                {{ numberToChinese(item.weightTime) }}磅重量：
                <div class="weight-number">{{ item.weight }}</div>
                {{ weightUnit }}
              </div>
              <div class="number" v-if="item.number">{{ item.number }}</div>
            </div>
          </div>
        </div>
        <div class="base-order selected" v-if="baseOrderNo">
          <div class="row">
            <div class="no">{{ baseOrderNo }}</div>
            <div class="status" :style="{ color: statusColor }">{{ statusName }}</div>
          </div>
          <div class="row">
            <div class="weight">
              {{ numberToChinese(weightTime) }}磅重量：
              <div class="weight-number">{{ weight }}</div>
              {{ weightUnit }}
            </div>
            <div class="number" v-if="number">{{ number }}</div>
          </div>
        </div>
        <div class="placeholder" v-if="type !== '4'"></div>
        <div class="re-capture" @click="reCapture" v-if="type === '2'">重新识别</div>
        <div class="footer" v-if="type !== '4'">
          <div class="submit btn" @click="confirm">确认</div>
        </div>
        <div class="footer" v-else>
          <div class="submit btn" @click="confirmRetail(1)" v-show="retailBaseOrders.length === 0">
            <div class="row1">初磅</div>
            <div class="row2">（无需选择单据）</div>
          </div>
          <div
            class="cancel btn"
            @click="confirmRetail(1)"
            v-show="retailBaseOrders.length !== 0 && !selectedBaseOrder"
          >
            <div class="row1">初磅</div>
            <div class="row2">（无需选择单据）</div>
          </div>

          <div class="submit btn" @click="confirmRetail(2)" v-show="retailBaseOrders.length !== 0">
            <div class="row1">确认</div>
            <div class="row2">（需先选择单据）</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { showToast, showNotify } from 'vant'
import api from '@/api/index'
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import successIcon from '@/assets/img/success-icon.svg'
import warnIcon from '@/assets/img/warn-icon.svg'
import { upload } from '@/libs/ali'
import { getWeightUnit, saveWeightToShow } from '@/libs/unit'
import { numberToChinese, getDayStart, getDayEnd } from '@/libs/utils'
import { getCodeValueAndColor } from '@/libs/code'
import qrCode from '@/assets/img/qr-code-white.svg'
import face from '@/assets/img/face-white.svg'
import idCard from '@/assets/img/id-card-white.svg'
import retail from '@/assets/img/retail-white.svg'
const router = useRouter()
const weightUnit = getWeightUnit()
const isRecognitionSuccessful = ref(false)
const capture = ref('')
const file1 = ref('')
const file2 = ref('')
const cusName = ref('')
const type = ref('')
const typeName = ref('')
const typeImg = ref('')
const baseOrderNo = ref('')
const number = ref('')
const weight = ref('')
const weightTime = ref(0)
const carNum = ref(0)
let inspectIndex = ref(1)
const nextCarNum = computed(() => carNum.value + (inspectIndex.value === 1 ? 1 : 0))
const statusName = ref('')
const statusColor = ref('')
let cusMsg = {}
let captureKey = ''
const retailBaseOrders = ref([])
async function init() {
  const inspectData = window.android.getInspectData()
  const json = JSON.parse(inspectData)
  capture.value = 'data:image/jpeg;base64,' + json.capture
  file1.value = 'data:image/jpeg;base64,' + json.file1
  file2.value = 'data:image/jpeg;base64,' + json.file2
  type.value = json.type
  const searchCusForm = {
    type: json.type,
    dbName: 'cusp'
  }
  switch (json.type) {
    case '1':
      typeName.value = '二维码'
      typeImg.value = qrCode
      switch (json.codeType) {
        case 'A':
          searchCusForm.cusIdCard = json.code
          searchCusForm.codeType = json.codeType
          break
        case 'B':
          searchCusForm.customerId = json.code
          searchCusForm.codeType = json.codeType
          break
      }
      break
    case '2':
      typeName.value = '人脸'
      typeImg.value = face
      captureKey = await upload(json.capture)
      searchCusForm.imageUrl = `${import.meta.env.VITE_INNER_FILE_DOMAIN}${captureKey}`
      break
    case '3':
      typeName.value = '证件'
      typeImg.value = idCard
      searchCusForm.cusIdCard = json.code
      break
    case '4':
      typeName.value = '散户'
      typeImg.value = retail
      break
    case '5':
      typeName.value = 'IC卡'
      typeImg.value = idCard
      searchCusForm.icCardNo = json.code
      break
  }
  // 散户过磅没有客商
  if (json.type !== '4') {
    api.cusproviderRecognizeSearch(searchCusForm).then(({ data: cus }) => {
      if (json.type === '2') {
        window.android.onRecognition(Boolean(cus))
      }
      if (!cus) {
        return
      }
      cusMsg = {
        cusId: cus.id,
        cusName: cus.cusName,
        cusMobile: cus.cusMobile,
        cusIdCard: cus.cusIdCard,
        cusTaxNum: cus.cusTaxNum,
        cusType: cus.cusType
      }
      cusName.value = cus.cusName
      isRecognitionSuccessful.value = true
      api
        .baseOrderStatistics({
          startDate: getDayStart(new Date()),
          endDate: getDayEnd(new Date()),
          cusId: cus.id
        })
        .then(({ data: res }) => {
          carNum.value = res.num
        })
      api.cusBaseOrders({ cusId: cus.id }).then(({ data: baseOrder }) => {
        if (baseOrder) {
          baseOrderNo.value = baseOrder.baseOrderNo
          number.value = baseOrder.number
          weight.value = saveWeightToShow(baseOrder.weightOut || baseOrder.weightIn)
          weightTime.value = baseOrder.materialInfo.length + 1
          const code = baseOrder.flow === '1' ? 'BASE_ORDER_IN_PROCESS' : 'BASE_ORDER_OUT_PROCESS'
          getCodeValueAndColor(code, baseOrder.process).then((res) => {
            statusColor.value = res.itemColor
            statusName.value = res.itemName
          })
          inspectIndex.value = 2
        }
      })
    })
  } else {
    cusName.value = '散户'
    api.retailBaseOrders({ flow: '1' }).then((res) => {
      if (!res.data) {
        res.data = []
      }
      retailBaseOrders.value = res.data
      retailBaseOrders.value.forEach((item) => {
        item.selected = false
        item.weight = saveWeightToShow(item.weightOut || item.weightIn)
        item.weightTime = item.materialInfo.length + 1
        const code = item.flow === '1' ? 'BASE_ORDER_IN_PROCESS' : 'BASE_ORDER_OUT_PROCESS'
        getCodeValueAndColor(code, item.process).then((res) => {
          item.statusColor = res.itemColor
          item.statusName = res.itemName
        })
      })
    })
  }
}
window.faceInit = init
if (window.android.faceInit) {
  window.android.faceInit()
}
onMounted(() => {
  // api.ocrCarNumber({ imageUrl: 'https://ghj-platform-file.oss-cn-shanghai.aliyuncs.com/test1.jpg' })

  const inspectData = window.android.getInspectData()
  const json = JSON.parse(inspectData)
  if (json.type !== '2') {
    init()
  }
})
const selectedBaseOrder = ref()
function retailSelected(item) {
  const selected = item.selected
  for (const val of retailBaseOrders.value) {
    val.selected = false
  }
  item.selected = !selected
  cusName.value = item.selected ? item.supplierName : '散户'
  selectedBaseOrder.value = item.selected ? item : null
}
function confirm() {
  const toast = showToast({
    type: 'loading',
    message: '加载中',
    forbidClick: true,
    overlay: true,
    duration: 0
  })
  router
    .replace({
      path: '/Weight',
      query: {
        isRecognitionSuccessful: isRecognitionSuccessful.value,
        cusMsg: JSON.stringify(cusMsg),
        captureKey,
        inspectIndex: inspectIndex.value,
        type: type.value
      }
    })
    .then(() => {
      toast.close()
    })
}
async function confirmRetail(index) {
  let id = ''

  cusMsg = {
    cusName: cusName.value
  }
  if (index === 2) {
    if (!selectedBaseOrder.value) {
      showNotify({
        message: '请先选择单据',
        type: 'warning'
      })
      return
    } else {
      id = selectedBaseOrder.value.id
      isRecognitionSuccessful.value = true
      const cusDetail = (await api.cusDetail({ id: selectedBaseOrder.value.supplierId })).data

      cusMsg = {
        cusId: cusDetail.id,
        cusName: cusDetail.cusName,
        cusMobile: cusDetail.cusMobile,
        cusIdCard: cusDetail.cusIdCard,
        cusType: cusDetail.cusType
      }
    }
  }
  const toast = showToast({
    type: 'loading',
    message: '加载中',
    forbidClick: true,
    overlay: true,
    duration: 0
  })
  router
    .replace({
      path: '/Weight',
      query: {
        isRecognitionSuccessful: isRecognitionSuccessful.value,
        cusMsg: JSON.stringify(cusMsg),
        inspectIndex: index,
        type: type.value,
        baseOrderId: id
      }
    })
    .then(() => {
      toast.close()
    })
}
function reCapture() {
  window.android.reCapture()
}
function faceCancel() {
  window.android.faceCancel()
}
</script>
<style lang="scss" scoped>
@import url('@/assets/style/mixins.scss');
@media screen and (max-width: 1080px) {
  .confirm {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    .body {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 0;
      align-items: center;
      flex: 1;
      .cus-msg {
        display: flex;
        flex-direction: column;
        align-items: center;
        .capture-retail {
          display: flex;
          width: 350px;
          height: 120px;
          justify-content: space-around;
          .capture-img {
            width: 160px;
            height: 120px;
            border: 1px solid;
          }
        }
        .capture {
          display: flex;
          width: 120px;
          height: 120px;
          position: relative;
          .capture-img {
            width: 120px;
            height: 120px;
            border-radius: 60px;
            border: 2px solid;
          }
          .is-success {
            width: 40px;
            height: 40px;
            position: absolute;
            right: 0;
            bottom: 0;
          }
        }
        .cus-name {
          font-size: 18px;
          margin: 20px 0 0;
        }
      }
      .other {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        flex: 1;
        height: 0;
        .tips {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          height: 26px;
          width: 100%;
          font-size: 15px;
          margin-bottom: 10px;
        }
        .msg {
          height: 26px;
          font-size: 15px;
        }
        .baseorders {
          flex: 1;
          overflow-y: auto;
          margin-bottom: 20px;
        }
        .base-order.selected {
          border-color: #1685fe;
        }
        .base-order {
          width: 283px;
          height: 76px;
          display: flex;
          flex-direction: column;
          margin-top: 14px;
          border: 2px solid #cccccc;
          border-radius: 6px;
          padding: 10px;
          .row {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            flex: 1;
            height: 0;
            .no {
              color: #02a7f0;
              font-size: 16px;
            }
            .cus-name {
              display: flex;
              justify-content: center;
              align-items: center;
              margin: 0;
              font-size: 16px;
            }
            .number {
              color: #333333;
              background-color: #44ed5f;
              text-align: center;
              padding: 2px;
              font-size: 14px;
              width: 80px;
              height: 20px;
              line-height: 20px;
              border-radius: 2px;
            }
            .weight {
              color: #333333;
              font-size: 16px;
              font-weight: bold;
              display: flex;
              align-items: center;
              .weight-number {
                font-size: 20px;
                display: flex;
                align-items: center;
              }
            }
            .status {
              width: 80px;
              height: 20px;
              font-weight: bold;
              line-height: 20px;
              text-align: center;
              font-size: 15px;
            }
          }
        }
        .placeholder {
          flex: 1;
        }

        .re-capture {
          color: #1685fe;
          text-decoration: underline #1685fe;
          font-size: 13px;
          margin-bottom: 22px;
        }
      }
    }
  }
}
@media screen and (min-width: 1920px) {
  .confirm {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    .body {
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 0;
      align-items: center;
      flex: 1;
      .cus-msg {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 139px;
        height: 100%;
        .capture-retail {
          display: flex;
          flex-direction: column;
          width: 83px;
          height: 0;
          justify-content: space-around;
          align-items: center;
          flex: 1;
          .capture-img {
            width: 83px;
            height: 57px;
          }
        }
        .capture {
          display: flex;
          width: 75px;
          height: 75px;
          position: relative;
          .capture-img {
            width: 75px;
            height: 75px;
            border-radius: 37.5px;
            border: 2px solid;
          }
          .is-success {
            width: 28px;
            height: 28px;
            position: absolute;
            right: 0;
            bottom: 0;
          }
        }
        .cus-name {
          font-size: 12px;
          margin: 9px 0 19px;
        }
      }
      .split {
        width: 1px;
        background-color: #1e98d7;
        margin: 7px 0;
        align-self: stretch;
      }
      .other {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        height: 100%;
        flex: 1;
        .tips {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          height: 15px;
          width: 100%;
          font-size: 9px;
          margin-bottom: 6px;
        }
        .msg {
          height: 15px;
          font-size: 9px;
        }
        .baseorders {
          flex: 1;
          overflow-y: auto;
        }
        .base-order.selected {
          border-color: #1685fe;
        }
        .base-order {
          width: 180px;
          height: 35px;
          display: flex;
          flex-direction: column;
          margin-bottom: 8px;
          border: 1px solid #cccccc;
          border-radius: 3px;
          padding: 6px;
          .row {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            flex: 1;
            height: 0;
            font-size: 9px;
            .no {
              color: #02a7f0;
            }
            .cus-name {
              display: flex;
              justify-content: center;
              align-items: center;
              margin: 0;
            }
            .number {
              color: #333333;
              background-color: #44ed5f;
              text-align: center;
              padding: 2px;
              font-size: 8px;
              width: 49px;
              height: 11px;
              line-height: 11px;
              border-radius: 1px;
            }
            .weight {
              color: #333333;
              font-size: 9px;
              font-weight: bold;
              display: flex;
              align-items: center;
              .weight-number {
                font-size: 15px;
                display: flex;
              }
            }
            .status {
              width: 40px;
              height: 10px;
              font-weight: bold;
              line-height: 10px;
              text-align: center;
            }
          }
        }
        .placeholder {
          flex: 1;
        }

        .re-capture {
          color: #1685fe;
          text-decoration: underline #1685fe;
          font-size: 8px;
          margin-bottom: 4px;
        }
      }
    }
  }
}
</style>
